package com.xiyu.service.repository.mailbox.mail;

import com.xiyu.service.model.mailbox.folder.MailboxFolderFetcher;
import com.xiyu.service.model.mailbox.mail.*;
import com.xiyu.service.vo.mailbox.mail.MailPageMailInput;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.Page;
import org.babyfish.jimmer.sql.ast.Predicate;

import java.util.List;

public interface MailboxMailApproveRepository extends JRepository<MailboxMailApprove, Long> {
    MailboxMailApproveTable mailboxMailApproveTable = MailboxMailApproveTable.$;

    default Page<MailboxMailApprove> pageMail(MailPageMailInput inputVO, List<Integer> statuses, Long creatorId, Long receiverId){
        return sql().createQuery(mailboxMailApproveTable)
                .whereIf(!statuses.isEmpty(), mailboxMailApproveTable.status().in(statuses))
                .where(mailboxMailApproveTable.creatorId().eqIf(creatorId))
                .whereIf(receiverId != null, mailboxMailApproveTable.receivers(receive -> Predicate.and(
                        receive.receiverId().eq(receiverId),
                        statuses.isEmpty() ? null : receive.approve().status().in(statuses)
                )))
                .whereIf(receiverId != null, mailboxMailApproveTable.mail().content().searchContent().likeIf(inputVO.getSearchContent()))
                .whereIf(inputVO.getSendTime() != null, () -> mailboxMailApproveTable.mail().sendTime().between(inputVO.getSendTime()[0], inputVO.getSendTime()[1]))
                .where(mailboxMailApproveTable.mail().subject().likeIf(inputVO.getSubject()))
                .orderBy(mailboxMailApproveTable.id().desc())
                .select(mailboxMailApproveTable.fetch(MailboxMailApproveFetcher.$.allTableFields()
                        .mail(MailboxMailFetcher.$.allTableFields()
                                .labels(MailboxMailLabelFetcher.$.labelFolder(MailboxFolderFetcher.$.name().color()))
                                .froms(MailboxMailFromFetcher.$.name()))
                ))
                .fetchPage(inputVO.getPageNo() - 1, inputVO.getPageSize());
    }

    default void updateStatus(List<Long> ids, Integer status){
        sql().createUpdate(mailboxMailApproveTable)
                .where(mailboxMailApproveTable.id().in(ids))
                .set(mailboxMailApproveTable.status(), status)
                .execute();
    }


}